/*
 * @(#)ProcessTask.java 2012-01-12
 *
 * Copyright 2011 北龙中网（北京）科技有限责任公司. All rights reserved.
 */
package cn.shangjia.shop.sync.process;

import static cn.shangjia.shop.sync.DataCenterConsumer.logger;
import static cn.shangjia.shop.sync.DataCenterConsumer.map;
import cn.shangjia.common.domain.Domain;
import cn.shangjia.common.mq.exec.message.KnetMessage;
import cn.shangjia.common.mq.message.DbMessageAction;
import cn.shangjia.common.mq.message.MessageBean;
import cn.shangjia.common.util.StringUtils;
import cn.shangjia.shop.exception.ShopSyncException;
import cn.shangjia.shop.service.MqLogService;
import cn.shangjia.shop.sync.service.SyncService;

/**
 *
 * @author <a href="mailto:jinzhongze@knet.cn">jinzhongze</a>
 * @version 1.0, 2012-01-12 09:52:22
 * @since 1.0
 */
public class ProcessTask implements Runnable {
	
	private MessageBean bean;
	private MqLogService mqLogService;
	private KnetMessage message;
	
	public ProcessTask(MessageBean bean, KnetMessage message, MqLogService mqLogService) {
		this.bean = bean;
		this.mqLogService = mqLogService;
		this.message = message;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void run() {
		
		//class
		Class<? extends Domain> clazz;
		try {
			clazz = (Class<? extends Domain>) Class.forName(bean.getClassName());
		} catch(Exception e) {
			logger.warn("[同步系统], class 类型错误 calzz : " , bean.getClassName());
			return;
		}
		if (clazz == null) {
			logger.warn("[同步系统], class 类型为空 : ");
			return;
		}
		//action
		DbMessageAction action = bean.getActionType();
		if (action == null) {
			logger.warn("[同步系统], action 类型为空 : ");
			return;
		}
		//beanid
		String beanId = bean.getBeanId();
		if (StringUtils.isEmpty(beanId)) {
			logger.warn("[同步系统], beanId 为空 : ");
			return;
		}
		//userId
		String userId = bean.getUserId();
		if (StringUtils.isEmpty(userId)) {
			logger.warn("[同步系统], userId 为空 : ");
			return;
		}
		
		//------------
		//service 
		if (!map.containsKey(clazz)) {
			logger.warn("[同步系统], 没有类型为[" + clazz + "]的解析服务!");
			return;
		}
		
		SyncService service = map.get(clazz); 
		
		
		//--执行同步 //TODO 错误日志 入库 有 主键约束.  这里也得改
		try {
			service.sync(action, beanId, userId);
		} catch (ShopSyncException sse) {
			logger.error(sse);
			mqLogService.addLog(message, sse.toString());
			return;
		} catch (Exception e) {
			logger.error(e);
			mqLogService.addLog(message, e.toString());
			return;
		}
		
		
	}

}
